package logic

import (
	"context"

	"mqtt/internal/svc"
	"mqtt/mqtt"

	"github.com/zeromicro/go-zero/core/logx"
)

type SubscribeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSubscribeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubscribeLogic {
	return &SubscribeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订阅主题
func (l *SubscribeLogic) Subscribe(in *mqtt.SubscribeRequest) (*mqtt.SubscribeResponse, error) {
	// 调用客户端管理器订阅主题
	subscribedCount, err := l.svcCtx.ClientMgr.Subscribe(in.ServerAddr, in.Topics, int32(in.Qos))
	if err != nil {
		return &mqtt.SubscribeResponse{
			Success: false,
			Error:   err.Error(),
		}, nil
	}

	return &mqtt.SubscribeResponse{
		Success:         true,
		SubscribedCount: int32(subscribedCount),
	}, nil
}
